<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="/shop/include :: header"></head>
<body>
<form class="layui-form" action="" lay-filter="shop_goods_category-add-form" style="margin-top: 20px;">
    <input type="hidden" name="id" th:value="${shopGoodsCategory.id}">
    <!--  -->
    <div style="display: flex">
        <!--  -->
        <div class="layui-form-item" style="display:contents;">
            <label class="layui-form-label">图标：</label>
            <div class="layui-upload-list" id="test1">
                <img class="layui-upload-img" id="demo1" th:src="${shopGoodsCategory.icon}"
                     style="width: 190px;height: 190px">
                <input type="hidden" name="icon" id="icon" th:value="${shopGoodsCategory.icon}">
            </div>
        </div>
        <div style="width: 73%">
            <!--  -->
            <div class="layui-form-item">
                <label class="layui-form-label">级别：</label>
                <div class="layui-input-block">
                    <select name="level" id="level" lay-verify="required|level" autocomplete="off"
                            placeholder="请选择分类级别" lay-filter="level"
                            class="layui-input" required="required">
                        <option th:selected="${shopGoodsCategory.level == 1}" value="1">一级</option>
                        <option th:selected="${shopGoodsCategory.level == 2}" value="2">二级</option>
                        <option th:selected="${shopGoodsCategory.level == 3}" value="3">三级</option>
                    </select>
                </div>
            </div>
            <!--  -->
            <div class="layui-form-item" id="dOneSelect" style="display: none">
                <label class="layui-form-label">一级分类：</label>
                <div class="layui-input-block">
                    <select name="oneLevelId" id="oneSelect" autocomplete="off"
                            placeholder="请选择一级分类" lay-filter="oneSelect"
                            class="layui-input">
                    </select>
                </div>
            </div>
            <!--  -->
            <div class="layui-form-item" id="dTwoSelect" style="display: none">
                <label class="layui-form-label">二级分类：</label>
                <div class="layui-input-block">
                    <select name="twoLevelId" id="twoSelect" autocomplete="off"
                            placeholder="请选择二级分类" lay-filter="oneLevelId"
                            class="layui-input">
                    </select>
                </div>
            </div>
            <!--  -->
            <div class="layui-form-item">
                <label class="layui-form-label">类别名称：</label>
                <div class="layui-input-block">
                    <input id="categoryName" name="categoryName" placeholder="请输入类别名称"
                           class="layui-input" lay-verify="required" autocomplete="off"
                           th:value="${shopGoodsCategory.categoryName}">
                </div>
            </div>
        </div>
    </div>
    <!--  -->
    <div class="layui-form-item">
        <label class="layui-form-label">权重：</label>
        <div class="layui-input-block">
            <input id="weight" name="weight" placeholder="请输入权重 最大排序越靠前"
                   class="layui-input" lay-verify="required" autocomplete="off" type="number"
                   th:value="${shopGoodsCategory.weight}">
        </div>
    </div>
    <!--  -->
    <div class="layui-form-item">
        <label class="layui-form-label">启用状态：</label>
        <div class="layui-input-block">
            <select name="enableState" id="enableState" lay-filter="enableState"
                    th:data="${shopGoodsCategory.enableState}">
            </select>
        </div>
    </div>
    <input type="hidden" name="specificationsId" id="specificationsId" th:value=${shopGoodsCategory.specificationsId}>
    <div class="layui-form-item" style="display: none" id="dSpecificationsId">
        <label class="layui-form-label">请选择规格</label>
        <div class="layui-input-block">
            <div id="specificationsIds" class="xm-select-demo" style="width: 891px"></div>
        </div>
    </div>
    <div class="layui-form-item" style="text-align: center">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit="" lay-filter="shop_goods_category-add">立即提交</button>
        </div>
    </div>
</form>
<div th:include="/shop/include::footer"></div>
<script src="../../../layuiadmin/modules/xmSelect.js"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    layui.use(['layer', 'jquery', 'form', 'laydate', 'upload', 'dict'], function () {
        var $ = layui.jquery;
        var laydate = layui.laydate;
        var layer = layui.layer;
        var form = layui.form;
        var upload = layui.upload;
        var dict = layui.dict;

        dict.setSelect("enableState", "enableState");
        ['showFolderIcon', 'showLine', 'strict'].forEach(function (key) {
            layui.form.on('checkbox(' + key + ')', function (data) {
                var treeConfig = {};
                treeConfig[key] = data.elem.checked;
                demo1.update({
                    tree: treeConfig
                })
            });
        })

        var specificationsIds = xmSelect.render({
            el: '#specificationsIds',
            autoRow: true,
            filterable: true,
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: [-3],
                strict: false
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            autoRow: true,
            filterable: true,
            height: 'auto',
            data: []
        })

        //查询一级分类
        $.ajax({
            url: '/platform/goodscategory/selectGoodsCategoryOfOne',
            type: "get",
            async: false,
            success: function (result) {
                if (result.status == "SUCCESS") {
                    if (result.data != null) {
                        var $html = "";
                        $.each(result.data, function (index, item) {
                            $html += "<option value='" + item.id + "'>" + item.categoryName + "</option>";
                        });
                        $("#oneSelect").html("<option value='0'>请选择</option>");
                        $("#oneSelect").append($html);
                        $("#oneSelect").val([[${shopGoodsCategory.oneLevelId}]])
                        form.render('select');
                        var value = $("#oneSelect").val();
                        if (value == undefined || value == 0) {
                            $("#twoSelect").html("<option value='0'>请选择</option>");
                            form.render('select');
                            return false;
                        }
                        $.ajax({
                            url: '/platform/goodscategory/selectGoodsCategoryOfTwoById?id=' + value,
                            type: "get",
                            async: false,
                            success: function (result) {
                                if (result.status == "SUCCESS") {
                                    if (result.data != null) {
                                        var $html = "";
                                        $.each(result.data, function (index, item) {
                                            $html += "<option value='" + item.id + "'>" + item.categoryName + "</option>";
                                        });
                                        $("#twoSelect").html("<option value='0'>请选择</option>");
                                        $("#twoSelect").append($html);
                                        $("#oneSelect").val([[${shopGoodsCategory.oneLevelId}]])
                                        $("#twoSelect").val([[${shopGoodsCategory.twoLevelId}]])
                                        form.render('select');
                                    }
                                } else {
                                    layer.msg(result.message)
                                }
                            }
                        });
                    }
                } else {
                    layer.msg(result.message)
                }
            }
        });

        $.ajax({
            url: '/platform/goodsspecifications/selectGoodsSpecificationsOfAll',
            type: "get",
            success: function (result) {
                var specificationsId = $("#specificationsId").val();
                var specificationsIdArr = specificationsId.split(",");
                var res = result.data;
                var str = "[";
                for (var i = 0; i < res.length; i++) {
                    if (specificationsIdArr.indexOf(res[i].id + "") >= 0) {
                        str += "{name: '" + res[i].specificationsName + "', value: " + res[i].id + ", selected: true, children:[";
                    } else {
                        str += "{name: '" + res[i].specificationsName + "', value: " + res[i].id + ", children:[";
                    }
                    for (var l = 0; l < res[i].list.length; l++) {
                        if (specificationsIdArr.indexOf(res[i].list[l].id + "") >= 0) {
                            str += "{name: '" + res[i].list[l].specificationsName + "', value: " + res[i].list[l].id + ", selected: true, },";
                        } else {
                            str += "{name: '" + res[i].list[l].specificationsName + "', value: " + res[i].list[l].id + ", },";
                        }
                    }
                    str += "]},"
                }
                str += "]";
                specificationsIds.update({
                    data: eval("(" + str + ")")
                })
            },
            error: function (result) {
                layer.msg("查询菜单失败")
            }
        });

        /*监听下拉框*/
        form.on('select(oneSelect)', function (dataObj) {
            var value = $("#oneSelect").val();
            if (value == undefined || value == 0) {
                $("#twoSelect").html("<option value='0'>请选择</option>");
                form.render('select');
                return false;
            }
            $.ajax({
                url: '/platform/goodscategory/selectGoodsCategoryOfTwoById?id=' + value,
                type: "get",
                async: false,
                success: function (result) {
                    if (result.status == "SUCCESS") {
                        if (result.data != null) {
                            var $html = "";
                            $.each(result.data, function (index, item) {
                                $html += "<option value='" + item.id + "'>" + item.categoryName + "</option>";
                            });
                            $("#twoSelect").html("<option value='0'>请选择</option>");
                            $("#twoSelect").append($html);
                            form.render('select');
                        }
                    } else {
                        layer.msg(result.message)
                    }
                }
            });
        });

        /*监听下拉框*/
        form.on('select(level)', function (dataObj) {
            var value = $("#level").val();
            if (value == 1) {
                $("#dOneSelect").css('display', 'none');
                $("#dTwoSelect").css('display', 'none');
                $("#dSpecificationsId").css('display', 'none');
            }
            if (value == 2) {
                $("#dOneSelect").css('display', 'block');
                $("#dTwoSelect").css('display', 'none');
                $("#dSpecificationsId").css('display', 'none');
            }
            if (value == 3) {
                $("#dOneSelect").css('display', 'block');
                $("#dTwoSelect").css('display', 'block');
                $("#dSpecificationsId").css('display', 'block');
            }
        });

        var level = [[${shopGoodsCategory.level}]];
        if (level == 1) {
            $("#dOneSelect").css('display', 'none');
            $("#dTwoSelect").css('display', 'none');
            $("#dSpecificationsId").css('display', 'none');
        }
        if (level == 2) {
            $("#dOneSelect").css('display', 'block');
            $("#dTwoSelect").css('display', 'none');
            $("#dSpecificationsId").css('display', 'none');
        }
        if (level == 3) {
            $("#dOneSelect").css('display', 'block');
            $("#dTwoSelect").css('display', 'block');
            $("#dSpecificationsId").css('display', 'block');
        }


        var uploadInst1 = upload.render({
            elem: '#test1'
            , url: '/platform/UploadFile' //改成您自己的上传接口
            //, headers: {"token": layui.data(layui.setter.tableName)['token']}
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.status != "SUCCESS") {
                    return layer.msg('上传失败');
                }
                //上传成功
                layer.msg('上传成功');
                $("#icon").val(res.data)
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst1.upload();
                });
            }
        });

        //监听提交
        form.on('submit(shop_goods_category-add)', function (data) {
            var selectArr = specificationsIds.getValue('valueStr');
            selectArr = JSON.stringify(selectArr, null, 2);
            selectArr = selectArr.replace(/"/g, "");
            $("#specificationsId").val(selectArr);
            data.field.specificationsId = selectArr
            $.ajax({
                url: '/platform/goodscategory/edit',
                type: "post",
                data: JSON.stringify(data.field),
                contentType: 'application/json; charset=utf-8', // 很重要
                async: false,
                success: function (result) {
                    if (result.status == "SUCCESS") {
                        layer.msg(result.message, {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            window.parent.location.reload();
                        });
                    } else {
                        layer.msg(result.message)
                    }
                }
            });
            return false;
        });
    });
</script>
</body>
</html>